package com.ziq.zcamp.post

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItem
import com.donkingliang.groupedadapter.adapter.GroupedRecyclerViewAdapter
import com.ziq.base.base.BaseFragment
import com.ziq.zcamp.R
import com.ziq.zcamp.databinding.FragmentSelectLocationCampBinding
import com.ziq.base.extension.*
import com.ziq.base.utils.permission.PermissionUtil
import com.ziq.zcamp.databinding.ItemLocationBinding
import com.ziq.zcamp.util.MapUtil
import com.ziq.zcamp.view.StatusView
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class SelectLocationPoiFragment : BaseFragment(R.layout.fragment_select_location_poi){

    private val binding: FragmentSelectLocationCampBinding? by binding()
    val mViewModel: SelectLocationPoiFragmentViewModel by viewModels()

    private var adapter : LocationAdapter? = null
    private var selectedItem : PoiItem? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    }

    fun selectLocationTabViewModel() : SelectLocationTabViewModel?{
        if(activity != null && activity is SelectLocationTabActivity){
            return (activity as SelectLocationTabActivity).mViewModel
        }
        return null
    }

    var isResume = false
    private var isFirst = true
    override fun onResume() {
        super.onResume()
        isResume = true
        if (isFirst){
            isFirst = false
            init()
        }
    }

    fun init(){
        binding?.recycleView?.layoutManager = LinearLayoutManager(context)
        adapter = LocationAdapter(context)
        binding?.recycleView?.adapter = adapter
        mViewModel.statusShow.observe(this, Observer<Int> {
            when(it){
                StatusView.IDLE -> {
                    binding?.statusView?.setStatus(StatusView.IDLE)
                }
                StatusView.LOADING -> {
                    binding?.statusView?.setStatus(StatusView.LOADING)
                }
                StatusView.NO_DATA -> {
                    binding?.statusView?.setStatus(
                        StatusView.NO_DATA,
                        isCenter = false,
                        marginTop = 86.dp,
                        imgSrc = R.drawable.pic_no_content_camp,
                        imgWidth = 235.dp,
                        imgHeight = 151.dp,
                        msg = "暂无相关内容哦～"
                    )
                }
                StatusView.NET_ERROR -> {
                    binding?.statusView?.setStatus(StatusView.NET_ERROR, updateActionBtn = { btn ->
                        btn.click {
                            mViewModel.onRefresh(true)
                        }
                    })
                }
            }
        })

        mViewModel.listRequestFinished.observe(this, Observer<Boolean> {
            if(it == true){
                binding?.refreshLayout?.finishRefresh()
                binding?.refreshLayout?.finishLoadMore()
            }
        })

        mViewModel.listHasMore.observe(this, Observer<Boolean> {
            if(it == true){
                binding?.refreshLayout?.resetNoMoreData()
            } else {
                binding?.refreshLayout?.setNoMoreData(true)
            }
        })

        mViewModel.list.observe(this, Observer<MutableList<PoiItem>> {
            adapter?.setData(it)
        })

        binding?.refreshLayout?.setOnRefreshListener {
            mViewModel.onRefresh(false)
        }
        binding?.refreshLayout?.setOnLoadMoreListener {
            mViewModel.onLoadMore()
        }
        binding?.root?.post {
            getLocation()
        }

        selectLocationTabViewModel()?.keyword?.observe(this, Observer<String> {
            mViewModel.keyword = it
            mViewModel.onRefresh(false)
        })
        selectLocationTabViewModel()?.poiItem?.observe(this, Observer<PoiItem?> {
            selectedItem = it
            adapter?.notifyDataChanged()
        })
    }

    override fun onPause() {
        super.onPause()
        isResume = false
    }


    @SuppressLint("CheckResult")
    fun getLocation(){
        binding?.statusView?.setStatus(StatusView.LOADING)
        PermissionUtil.requestLocationPermission(requireActivity(), onGrant = {
            MapUtil.getCurrentLocation(callback = {
                if(mViewModel.myLatLng == null){
                    mViewModel.myLatLng = LatLonPoint(it.latitude, it.longitude)
                    mViewModel.onRefresh(true)
                }
            }, onFail = {
                mViewModel.onRefresh(true)
            })
        }, onReject = {
            mViewModel.onRefresh(true)
        }, onRemind = {
            mViewModel.onRefresh(true)
        })
    }

    inner class LocationAdapter(context: Context?) : GroupedRecyclerViewAdapter(context){

        val locationList : MutableList<PoiItem> = mutableListOf()

        fun setData(list : MutableList<PoiItem>){
            locationList.clear()
            locationList.addAll(list)
            notifyDataChanged()
        }

        override fun getGroupCount(): Int {
            return 1
        }

        override fun getChildrenCount(groupPosition: Int): Int {
            return locationList.size
        }

        override fun hasHeader(groupPosition: Int): Boolean {
            return false
        }

        override fun hasFooter(groupPosition: Int): Boolean {
            return false
        }

        override fun getHeaderLayout(viewType: Int): Int {
            return R.layout.item_select_location_header
        }

        override fun getChildLayout(viewType: Int): Int {
            return R.layout.item_location
        }

        override fun getFooterLayout(viewType: Int): Int {
            return 0
        }

        override fun onBindHeaderViewHolder(holder: com.donkingliang.groupedadapter.holder.BaseViewHolder?, groupPosition: Int) {
        }


        override fun onBindChildViewHolder(
            holder: com.donkingliang.groupedadapter.holder.BaseViewHolder?,
            groupPosition: Int,
            childPosition: Int
        ) {
            holder?.let {
                val binding = ItemLocationBinding.bind(holder.itemView)
                val item = locationList[childPosition]
                binding.name.text = "${item.title}"
                binding.location.text = "${item.provinceName?:""}${item.cityName?:""}${item.adName?:""}${item.snippet}"
                binding.status.visibility = if(item.poiId == selectedItem?.poiId) View.VISIBLE else View.GONE
                binding.root.click {
                    selectLocationTabViewModel()?.campInfo?.postValue(null)
                    selectLocationTabViewModel()?.poiItem?.postValue(item)
                }
            }
        }

        override fun onBindFooterViewHolder(holder: com.donkingliang.groupedadapter.holder.BaseViewHolder?, groupPosition: Int) {
        }

    }
}